//
//  MyReservationListViewController My reservation list.swift
//  koolcar
//
//  Created by xiantian on 2023/10/30.
//

import UIKit
import MJRefresh

class MyReservationViewController: BaseViewController {
    var emptyView: LYEmptyView!
    var tableView: BaseTableView!
    var dataArray = NSMutableArray()
    var pageNumber: NSInteger = 1
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.title = MMLocalizedString("my_appointment", comment: "我的预约")
        self.navBar.wr_setBottomLineHidden(hidden: true)
        self.view.backgroundColor = Theme.viewBkgGrayColor
        
        tableView = BaseTableView.init(frame: CGRect.init(x: 0, y: NavBarHight, width: kScreenWidth, height: kScreenHeight - NavBarHight), style: .plain)
        tableView.register(MyReservationCell.self, forCellReuseIdentifier: "MyReservationCell")
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "space")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.backgroundColor = Theme.viewBkgGrayColor
        tableView.separatorStyle = .none
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 165
        self.view.addSubview(tableView)
        
        self.setUpNoData()
        
        self.addPullRefreash()
        self.addLoadMoreRefreash()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        var vcArray = self.navigationController?.viewControllers ?? []
        guard vcArray.count > 1 else {
            return
        }
        let findObj = vcArray.first(where: {($0 as? MSServiceSuccessViewController) != nil})
        if findObj != nil {
            //说明找到了MSServiceSuccessViewController要将其移除掉
            vcArray.remove(at: vcArray.count - 2)
            self.navigationController?.viewControllers = vcArray
        }
    }
    
    /*
     * 添加头部刷新
     */
    func addPullRefreash()  {
        weak var weakself = self
        let header = MJRefreshNormalHeader.init(refreshingBlock: {
            weakself?.pageNumber = 1
            weakself?.requestReservation(isMore: false)
        })
        header?.activityIndicatorViewStyle = .gray
        self.tableView.mj_header = header
        self.tableView.mj_header.beginRefreshing()
    }
    
    
    //MARK: -  底部刷新
    func addLoadMoreRefreash()  {
        weak var weakself = self
        let footer = MJRefreshBackNormalFooter.init(refreshingBlock: {
            weakself?.pageNumber = weakself!.pageNumber + 1
            weakself?.requestReservation(isMore: true)
        })
        self.tableView.mj_footer = footer
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -100
        self.tableView.ly_emptyView = self.emptyView
    }

    
    ///获取预约服务
    private func requestReservation(isMore: Bool){
        if self.pageNumber == 1 {
            self.tableView.mj_footer.resetNoMoreData()
        }
        let param: [String: String] = [
            "pageSize":"20",
            "pageNumber": "\(self.pageNumber)"
        ]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingOrderManagerPage(param: param), objectType: MyReservationResModel.self) { data in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            let resultObj = data as? MyReservationResModel
            if resultObj?.code == "1" {
                let tempArr = resultObj?.data?.content ?? []
                if isMore == false {
                    self.dataArray.removeAllObjects()
                }
                tempArr.forEach { item in
                    item.cancelBlock = {[weak self] in
                        self?.didSelectCancelBtnAction(orderModel: item)
                    }
                }
                self.dataArray.addObjects(from: tempArr)
                if resultObj?.data?.total == self.dataArray.count {
                    self.tableView.mj_footer.endRefreshingWithNoMoreData()
                }
                self.tableView.reloadData()
            }else{
                self.view.makeToast(message: resultObj?.msg ?? "")
            }
        } error: { err in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///取消预约
    private func didSelectCancelBtnAction(orderModel: MyReservationContentModel){
        ServiceAlertView.showAlertView(title: MMLocalizedString("hint", comment: "提示"),
                                       message: MMLocalizedString("my_reserver_cancel_tip", comment: "确定取消预约吗？"),
                                    cancelButtonTitle: MMLocalizedString("cancel", comment: "取消"),
                                       otherButtonTitlesArr: [MMLocalizedString("confirm", comment: "确定")]) { [weak self] (tagIndex, _) in
            if tagIndex == 1 {
                self?.cancelReserverRequest(item: orderModel)
            }
        }
    }
    
    ///取消预约订单 status: 2 表示用户自己取消
    private func cancelReserverRequest(item: MyReservationContentModel){
        let param: [String: String] = ["id": "\(item.id ?? 0)",
                                       "status":"2"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingOrderManagerUpdate(param: param), objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
               let firObj = self.dataArray.map{$0 as! MyReservationContentModel}.first(where: {$0.id == item.id})
                firObj?.status = 2
                self.tableView.reloadData()
                self.view.makeToast(message: MMLocalizedString("my_reserver_canceled", comment: "已取消预约"))
            }else{
                self.view.makeToast(message: resultObj.msg ?? "")
            }
        } error: { err in
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
}

/**
 private func cancelReserverRequest(item: MyReservationContentModel){
     let param: [String: String] = ["id": "\(item.serverId ?? 0)"]
     XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.bookingOrderManagerDetail(param: param), objectType: CommondResModel.self) { data in
         let resultObj = data as! CommondResModel
         if resultObj.code == "1" {
            let firObj = self.dataArray.map{$0 as! MyReservationContentModel}.first(where: {$0.id == item.id})
             firObj?.status = 2
             self.tableView.reloadData()
             self.view.makeToast(message: MMLocalizedString("my_reserver_canceled", comment: "已取消预约"))
         }else{
             self.view.makeToast(message: resultObj.msg ?? "")
         }
     } error: { err in
         self.view.makeToast(message: err?.domain ?? "")
     }
 }
 */

extension MyReservationViewController: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArray.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return IphoneXMarginBottom + 4
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MyReservationCell", for: indexPath) as! MyReservationCell
        if self.dataArray.count > indexPath.row {
            let itemModel = self.dataArray[indexPath.row]
            cell.setMyReservationCell(data: itemModel as! MyReservationContentModel)
        }
        cell.selectionStyle = .none
        cell.clipsToBounds = true
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        tableView.deselectRow(at: indexPath, animated: false)
//
//
//        ServiceAlertView.showAlertView(title: MMLocalizedString("add_tip", comment: "提示"),
//                                    message: "确定取消预约吗？",
//                                    cancelButtonTitle: "取消", otherButtonTitlesArr: ["确定"]) { [weak self] (tagIndex, _) in
//        }
        
    }
}
